package com.sea.base.utils

import android.Manifest
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.os.Build
import android.provider.MediaStore
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.sea.base.ext.global.singleApplication
import com.sea.base.ext.global.toast
import com.sea.base.ext.view.requireActivity
import com.sea.base.ui.requestMajorPermission
import java.io.File

@JvmOverloads
fun String?.downloadBitmap(ui: com.sea.base.ui.IUIContext, toastSt: CharSequence = "保存图片成功") {
    if (this.isNullOrEmpty()) {
        "图片为空，保存失败！".toast()
        return
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
        ui.requestMajorPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE).startRequest {
            downloadAndSave(ui, this, toastSt)
        }
    } else {
        downloadAndSave(ui, this, toastSt)
    }
}

private fun downloadAndSave(ui: com.sea.base.ui.IUIContext, url: String, toastSt: CharSequence) {
    Glide.with(ui.requireActivity).downloadOnly().load(url).into(object : CustomTarget<File>() {

        override fun onLoadFailed(errorDrawable: Drawable?) {
            "图片下载失败！".toast()
        }

        override fun onLoadCleared(placeholder: Drawable?) {
        }

        override fun onResourceReady(resource: File, transition: Transition<in File>?) {
            try {
                val contentValues = ContentValues()
                //这段代码是添加自己保留的标签，自己可以后续处理，暂时无用
//                    contentValues.put(
//                        MediaStore.MediaColumns.DISPLAY_NAME,
//                        "${Environment.DIRECTORY_PICTURES}/test${System.currentTimeMillis()}"
//                    )
                contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
                singleApplication.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let { uri ->
                    singleApplication.contentResolver.openOutputStream(uri)?.use {
                        BitmapFactory.decodeFile(resource.absolutePath).compress(Bitmap.CompressFormat.JPEG, 100, it)
                    }
                    toastSt.toast()
                } ?: "图片保存到图库失败！".toast()
            } catch (e: Throwable) {
                "图片保存失败！".toast()
                e.printStackTrace()
            }
        }
    })

}